<template>
  <TopHeader>
    <template #addCity>
      <el-button class="add-btn" @click="addCity"> + </el-button>
    </template>
  </TopHeader>
  <!-- 城市天气信息 -->
  <div class="container">
    <div class="header-msg wrap">
      你正在预览{{ city }}的天气信息，可以通过右上角的"+"号按钮保存起来
    </div>
    <div class="tody">
      <div>当日气温是: {{ weatherNow.temperature }}摄氏度</div>
      <div>当日天气是：{{ weatherNow.weather }}</div>
      <div>当日风向是：{{ weatherNow.winddirection }}风</div>
      <div>当日风力是: {{ weatherNow.windpower }}级</div>
    </div>
  </div>
  <weather-forecast />
</template>

<script setup>
import { getAdcodeApi, getWeatherNowApi } from '@/api/weather'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useCityStore } from '@/stores'
import router from '@/router'
const route = useRoute()
// 接收home的路由传参
const city = route.query.city
// 创建仓库实例
const cityStore = useCityStore()
// console.log(cityStore.cityList)
// 定义城市code和实况天气
const adCode = ref(0)
const weatherNow = ref({})
// 定义添加城市的方法
const addCity = () => {
  // 定义成员
  const cityItem = {
    id: +new Date(),
    city: city,
    daytemp: weatherNow.value.temperature,
  }
  // 判断仓库中是否有此页面中的城市
  const res = cityStore.cityList.some(item => item.city === city)
  // 如果没有就添加成员
  if (!res) {
    cityStore.cityList.push(cityItem)
  }else {
    alert('您已经添加过该城市了')
  }
  // 跳转主路由
  router.push('/')
}
onMounted(async () => {
  // 根据当前城市名字更新城市code
  const codeRes = await getAdcodeApi(city)
  adCode.value = codeRes.geocodes[0].adcode
  // 根据城市code获取实况天气
  const WeatherNowRes = await getWeatherNowApi(adCode.value)
  weatherNow.value = WeatherNowRes.lives[0]
  console.log(weatherNow.value)
})
</script>

<style lang="scss" scoped>
.add-btn {
  width: 30px;
  height: 30px;
  border-radius: 30px;
}
.container {
  color: #fff;
  font-size: 16px;
  .header-msg {
    height: 60px;
    line-height: 60px;
    text-align: center;
    background-color: #004e71;
  }
  .tody {
    text-align: center;
    border-bottom: 1px solid #838383;
    div {
      margin: 20px 0;
    }
  }
}
</style>
